<template>
  <el-form ref="formRef" :model="form" label-width="80px" :disabled="viewType === 'read'">
    <el-row>
      <el-col :span="24">
        <el-form-item label="标题" prop="title"
                      :rules="{ required: true, message: '标题不能为空', trigger: 'blur'}">
          <el-input v-model="form.title" placeholder="请输入标题"/>
        </el-form-item>
      </el-col>
      <el-col :span="24" >
        <el-row :gutter="10" v-for="(field, index) in form.dynamicFields">
          <el-col :span="7">
            <el-form-item
                style="width: 100%;"
                :label="'字段' + (index+1)"
                :key="field.key"
                :prop="'dynamicFields.' + index + '.fieldName'"
                :rules="{ required: true, message: '字段不能为空', trigger: 'blur'}"
            >
              <el-input placeholder="字段名" v-model="field.fieldName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item
                :label="'字段' + (index+1)"
                :key="field.key"
                :prop="'dynamicFields.' + index + '.fieldKey'"
                :rules="{ required: true, message: '字段不能为空', trigger: 'blur'}"
            >
              <el-input placeholder="字段标识" v-model="field.fieldKey"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item
                :label="'字段' + (index+1)"
                :key="field.key"
                :prop="'dynamicFields.' + index + '.fieldValue'"
                :rules="{ required: true, message: '字段不能为空', trigger: 'blur'}"
            >
              <el-input placeholder="字段值" v-model="field.fieldValue"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-button @click.prevent="removeField(field)" v-if="viewType !== 'read'" type="danger">删除</el-button>
          </el-col>
        </el-row>
      </el-col>

      <el-col :span="24" class="text-left" v-if="viewType !== 'read'">
        <el-button type="primary" @click="addField">新增字段</el-button>
      </el-col>
    </el-row>
  </el-form>
</template>

<script setup name="ProcessForm">
import {getFlowablePlusFormInfoByProcessInstanceId, startProcessInstanceByKey} from "@/api/process/process.js";
const { proxy } = getCurrentInstance();
const procInstId = ref('');
const modelKey = ref('');
const currModel = ref(undefined);
// 遮罩层
const loading = ref(true);
const props = defineProps({
  modelKey: undefined,
  procInstId: undefined,
  taskId: undefined,
  bizKey: undefined,
  viewType: undefined,  // read
})
// 表单参数
const data = reactive({
  form: {
    title: '',
    dynamicFields: []
  }
});

const { form } = toRefs(data);

const removeField = (item) => {
  const index = form.value.dynamicFields.indexOf(item)
  if (index !== -1) {
    form.value.dynamicFields.splice(index, 1)
  }
}
const addField = () => {
  console.log(form.value);
  form.value.dynamicFields.push({
    fieldName: '',
    fieldKey: '',
    fieldValue: '',
    value: '',
    key: Date.now()
  });
}
const submitForm = () => {
  proxy.$refs["formRef"].validate(valid => {
    console.log('=================>', valid);
    if (valid) {
      // 组装流程/表单参数
      const params = genSaveData();
      // 发起流程
      // this.submitLoading = true;
      startProcessInstanceByKey(params).then(res =>{
        if(res.success){
          proxy.$modal.msgSuccess(res.msg);
          setTimeout(()=>{
            // this.$router.replace('/process/launched');
            // this.submitLoading = false;
          }, 1000)
        }else{
          // message.error(res.msg);
          // proxy.$modal.msgError(res.msg);
          // this.submitLoading = false;
        }
      }).catch(e=>{
        proxy.$modal.msgError("流程发起失败！");
        // this.submitLoading = false;
        // message.error("流程发起失败！");
      });
    } else {
      activeTabName.value = 'formInfo'
    }
  }).catch(e=>{
    console.error(e);
  });
}

const genSaveData = () => {
  const data = {
    modelKey: currModel.value.modelKey,
    currentUserCode: '1',
    businessKey: 'test_businessKey' + (new Date()).getTime(),
    creator: '1',
    appSn: 'flow',
    message: '发起流程',
    formName: form.title
  };
  data.formData = JSON.stringify({...data, ...form.value});
  if(form.value.dynamicFields.length > 0){
    const variables = {};
    form.value.dynamicFields.forEach(item => {
      variables[item.fieldName] = item.fieldValue;
    })
    data.variables = variables;
  }
  console.log(data);
  return data;
}

const resetForm = () => {
  form.value = {
    id: undefined,
    title: undefined,
    dynamicFields: []
  };
  proxy.resetForm("formRef");
}

async function formValid(){
  return proxy.$refs["formRef"].validate();
}
async function getFormData(){
  const valid = await proxy.$refs["formRef"].validate();
  if(valid){
    return form.value;
  }
  return undefined;
}

function initFormData() {
  if (props.procInstId) {
    getFlowablePlusFormInfoByProcessInstanceId({procInstId: props.procInstId}).then(resData => {
      const {formData} = resData.data;
      form.value = JSON.parse(formData);
    }).catch(e => {
    });
  } else {
    form.value = {};
  }
}

watch(() => props.procInstId, procInstId => {
  if (procInstId) {
    initFormData();
  }
},{ immediate: true });


defineExpose({
  resetForm,
  getFormData,
  formValid
})

</script>

<style lang="scss">

.launch-wrapper {
  .el-dialog__body {
    position: relative;
    padding: 0 20px;

    .right-btn {
      position: absolute;
      right: 10px;
      top: 0px;
    }
  }

}

</style>
